package nl.renedegroot.android.intervalbeeper;

import java.util.Iterator;
import java.util.Timer;
import java.util.Vector;

import nl.renedegroot.android.intervalbeeper.widget.NumberPicker;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class IntervalAdapter extends BaseAdapter implements Iterable<SoundTimer>
{
   private boolean playing = false;
   Vector<SoundTimer> mTasks = new Vector<SoundTimer>();
   private Context mContext;

   IntervalAdapter( Context context )
   {
      mContext = context;
   }
   
   public void add( SoundTimer timerTask )
   {
      mTasks.add( timerTask );
      this.notifyDataSetChanged();
   }
   
   public void startAll(Timer timer)
   {
      playing = true;
      for( SoundTimer soundTimer : mTasks )
      {
         soundTimer.setTimer(timer);
      }
   }
   
   public void update()
   {
      this.notifyDataSetChanged();
   }
   
   public void removeOne( int position )
   {
      SoundTimer task = mTasks.remove( position );
      task.cancel();
      this.notifyDataSetChanged();
   }
   
   public void removeAll()
   {
      resetAll();
      mTasks.setSize( 0 );
      this.notifyDataSetChanged();
   }   
   
   public void resetAll()
   {
      playing = false;
      for( SoundTimer task : mTasks )
      {
         task.cancel();
         task.setTimer(null);
      }
   }
   public Iterator<SoundTimer> iterator()
   {
      return mTasks.iterator();
   }
   
   public boolean isPlaying()
   {
      return playing;
   }

   public int getCount()
   {
      return mTasks.size();
   }

   public Object getItem( int position )
   {
      return mTasks.get( position );
   }

   public long getItemId( int position )
   {
      return position;
   }

   public View getView( int position, View convertView, ViewGroup parent )
   {
      TextView view ;
      if( convertView == null )
      {
         LayoutInflater factory = LayoutInflater.from( mContext );
         view = (TextView) factory.inflate( R.layout.interval_row, null );
      }
      else
      {
         view = (TextView)convertView;
      }
      view.setText( mTasks.get( position ).toString() );
      return view;
   }
}
